;$(function () {
    layui.use(['form', 'table', 'laydate'], function () {
        var form = layui.form,
            table = layui.table,
            laydate = layui.laydate;
        form.verify({
            positiveInteger: [
                /^[+]{0,1}(\d+)$/ //正则表达式
                , '只能是数字' //提示信息
            ],
            money: [
                /^[0-9]{1,}\.[0-9]{2}$/ //正则表达式
                , '金额格式错误' //提示信息
            ]
        });

        table.render({
            elem: '#waresTable'
            , method: "post"
            , url: 'getWarsList'
            , response: {
                statusCode: true
            }
            , where: {
                id: $("#waresIdOrNameVal").val(),
                category1: $("#category1").val(),
                category2: $("#category2").val(),
                waresStatus: $("#waresStatus").val(),
            }
            , defaultToolbar: []
            , cellMinWidth: 80
            , cols: [[
                {field: 'sorts', title: '序号', event: "checkChange", templet: '#sort', width: 58, align: 'center'}
                , {field: 'id', title: '条码', event: "checkChange", align: 'center', width: 83}
                , {field: 'name', title: '名称', event: "checkChange", align: 'center'}
                , {field: 'specification', title: '规格', event: "checkChange", align: 'center', width: 100}
                , {field: 'category', event: "checkChange", title: '分类', align: 'center', width: 150}
                , {field: 'unit', event: "checkChange", title: '单位', align: 'center', width: 80}
                , {field: 'inventory', title: '库存', event: "checkChange", align: 'center', width: 85}
                , {
                    field: 'purchase', title: '进价(元)', event: "checkChange", align: 'center', templet: function (d) {
                        return d.purchase.toFixed(2);
                    }
                }
                , {
                    field: 'price', title: '售价(元)', event: "checkChange", align: 'center', templet: function (d) {
                        return d.price.toFixed(2);
                    }
                }
                , {field: 'saleVolumes', title: '销量', event: "checkChange", sort: true, align: 'center', width: 85}
                , {
                    field: 'tool', title: '操作', align: 'center', width: 120,
                    templet: function (d) {
                        return '<span style="text-decoration:underline;cursor:pointer;color:#4BB2FF" lay-event="edit">编辑</span>'
                            + '<span style="margin-left:10px;text-decoration:underline;cursor:pointer;color:#D92E2E" lay-event="del">删除</span>'
                    }
                }

            ]]
            , page: true
            , id: 'waresRender'
        });

        $("#waresIdOrNameBtn").click(function () {
            table.reload('waresRender', {
                where: {
                    id: $("#waresIdOrNameVal").val(),
                    category1: $("#category1").val(),
                    category2: $("#category2").val(),
                    waresStatus: $("#waresStatus").val(),
                },
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
        });
        form.on('select(Category1)', function (CategoryData) {
            $("#category2").empty();
            $("#category2").append("<option value=''>全部</option>");
            let firstCategoryId = CategoryData.value;
            if (firstCategoryId !== "") {
                $.ajax({
                    url: 'getCategory2',
                    type: "post",
                    dataType: "json",
                    data: {
                        "firstCategoryId": firstCategoryId
                    },
                    async: false,
                    success: function (result) {
                        if (result.code === true) {
                            for (var i = 0; i < result.category2.length; i++) {
                                $("#category2").append("<option value=" + result.category2[i].categoryId + ">" + result.category2[i].categoryName + "</option>")
                            }
                        } else {
                            layer.msg(result.msg);
                        }
                    }, error: function () {
                        layer.msg("拉取失败，稍后再试");
                    }
                });
            }
            form.render('select');
            $("#waresIdOrNameBtn").click();
        });
        form.on('select(WaresEditCategory1)', function (CategoryData) {
            $("#WaresEditCategory2").empty();
            let firstCategoryId = CategoryData.value;
            if (firstCategoryId !== "") {
                $.ajax({
                    url: 'getCategory2',
                    type: "post",
                    dataType: "json",
                    data: {
                        "firstCategoryId": firstCategoryId
                    },
                    async: false,
                    success: function (result) {
                        if (result.code === true) {
                            for (var i = 0; i < result.category2.length; i++) {
                                $("#WaresEditCategory2").append("<option value=" + result.category2[i].categoryId + ">" + result.category2[i].categoryName + "</option>")
                            }
                        } else {
                            layer.msg(result.msg);
                        }
                    }, error: function () {
                        layer.msg("拉取失败，稍后再试");
                    }
                });
            }
            form.render('select');
        });
        form.on('select(WaresAddCategory1)', function (CategoryData) {
            $("#WaresAddCategory2").empty();
            let firstCategoryId = CategoryData.value;
            if (firstCategoryId !== "") {
                $.ajax({
                    url: 'getCategory2',
                    type: "post",
                    dataType: "json",
                    data: {
                        "firstCategoryId": firstCategoryId
                    },
                    async: false,
                    success: function (result) {
                        if (result.code === true) {
                            for (var i = 0; i < result.category2.length; i++) {
                                $("#WaresAddCategory2").append("<option value=" + result.category2[i].categoryId + ">" + result.category2[i].categoryName + "</option>")
                            }
                        } else {
                            layer.msg(result.msg);
                        }
                    }, error: function () {
                        layer.msg("拉取失败，稍后再试");
                    }
                });
            }
            form.render('select');
        });
        form.on('select(Category2)', function () {
            form.render('select');
            $("#waresIdOrNameBtn").click();
        });
        form.on('select(waresStatus)', function () {
            form.render('select');
            $("#waresIdOrNameBtn").click();
        });
        $(".UnitAdd").click(function () {
            layer.prompt({
                formType: 0
                , title: '创建新单位：'
                , value: ""
            }, function (value, index) {
                if (value != null) {
                    $.post('insertUnit', {
                        unit: value
                    }, function (result) {
                        if (result.code === true) {
                            layer.msg("创建成功");
                            getAllUnit();
                            form.render("select");
                        } else {
                            layer.msg(result.msg);
                        }
                    });
                }
                layer.close(index);
            });
        });

        function getAllUnit() {
            $(".waresUnit").empty();
            $.ajax({
                async: false,
                url: "getUnit",
                type: "POST",
                dataType: "json",
                success: function (result) {
                    if (result.code === true) {
                        for (let i = 0; i < result.unit.length; i++) {
                            $(".waresUnit").append("<option value=" + result.unit[i].id + ">" + result.unit[i].unit + "</option>")
                        }
                        form.render("select");
                    } else {
                        layer.msg(result.msg);
                    }
                },
                error: function () {
                    layer.msg("网络异常，请稍后再试")
                }
            });
        }

        table.on('tool(waresTable)', function (obj) {
            let data = obj.data;
            switch (obj.event) {
                case 'del':
                    layer.confirm('真的要删除吗？', function (index) {
                        $.ajax({
                            async: false,
                            url: "deleteWares",
                            data: {
                                id: data.id
                            },
                            type: "POST",
                            dataType: "json",
                            success: function (result) {
                                if (result.code === true) {
                                    layer.msg("删除成功");
                                    obj.del();
                                }
                            },
                            error: function () {
                                layer.msg("网络异常，请稍后再试")
                            }
                        });
                        layer.close(index);
                    });
                    break;
                case 'edit':
                    $('#waresEditView')[0].reset();
                    form.val("waresEditView", {
                        "id": data.id,
                        "name": data.name,
                        "specification": data.specification,
                        "inventory": data.inventory,
                        "freshDate": data.freshDate,
                        "expiryDate": data.expiryDate,
                        "purchase": data.purchase.toFixed(2),
                        "price": data.price.toFixed(2),
                    });
                    $("#WaresEditCategory1").empty();
                    $("#WaresEditCategory1").append($("#category1").find("*[value!='']").clone(true));
                    let category1 = "";
                    if (!isEmpty(data.category)) {
                        category1 = data.category.split("-")[0];
                    }
                    $("#WaresEditCategory1 option").each(function () {
                        let text = $(this).text();
                        let value = $(this).val();
                        if (category1 === text) {
                            $("#WaresEditCategory1").val(value);
                        }
                    });
                    $.ajax({
                        url: 'getCategory2',
                        type: "post",
                        dataType: "json",
                        data: {
                            "firstCategoryId": $("#WaresEditCategory1").val()
                        },
                        async: false,
                        success: function (result) {
                            if (result.code === true) {
                                $("#WaresEditCategory2").empty();
                                for (var i = 0; i < result.category2.length; i++) {
                                    $("#WaresEditCategory2").append("<option value=" + result.category2[i].categoryId + ">" + result.category2[i].categoryName + "</option>")
                                }
                            } else {
                                layer.msg(result.msg);
                            }
                        }, error: function () {
                            layer.msg("拉取失败，稍后再试");
                        }
                    });
                    let category2 = "";
                    if (!isEmpty(data.category)) {
                        category2 = data.category.split("-")[1];
                    }
                    // let category2 = data.category.split("-")[1];
                    $("#WaresEditCategory2 option").each(function () {
                        let text = $(this).text();
                        let value = $(this).val();
                        if (category2 === text) {
                            $("#WaresEditCategory2").val(value);
                        }
                    });
                    getAllUnit();
                    $("#WaresEditUnit option").each(function () {
                        let text = $(this).text();
                        let value = $(this).val();
                        if (data.unit === text) {
                            $("#WaresEditUnit").val(value);
                        }
                    });
                    form.render(null, 'waresEditView');
                    let formInit = $("#waresEditView").serializeArray();
                    let TextInit = JSON.stringify({dataform: formInit});
                    layer.open({
                        type: 1,
                        title: "编辑商品信息",
                        skin: 'layui-layer-rim',//加边框
                        area: ['500px', '550px'],
                        content: $("#WareEditView"),//注意放在<body>最外层
                        btn: ['确认', '取消'],
                        yes: function (index1, layero) {
                            if (freshCheck("#WareEditView")) {
                                let formInit2 = $("#waresEditView").serializeArray();
                                let TextInit2 = JSON.stringify({dataform: formInit2});
                                if (TextInit === TextInit2) {
                                    layer.close(index1);
                                } else {
                                    form.on('submit(waresEditView)', function () {
                                        $("#waresEditView").ajaxSubmit({
                                            type: 'POST',
                                            url: "updateWares",
                                            dataType: 'json',
                                            success: function (result) {
                                                if (result.code === true) {
                                                    layer.close(index1);
                                                    table.reload('waresRender');
                                                } else {
                                                    layer.msg(result.msg);

                                                }

                                            },
                                        });
                                        return false;   //防止表单自动提交
                                    });
                                    $("#waresEditView").submit();
                                }
                            }

                        },
                        btn2: function (index, layero) {
                            layer.close(index);
                        },
                    });
                    break;
            }
        });

        $("#waresAdd").click(function () {
            let waresId = "";
            $('#waresAddView')[0].reset();
            $("#WaresAddCategory1").empty();
            $("#WaresAddCategory1").append($("#category1").find("*[value!='']").clone(true));
            $.ajax({
                url: 'getCategory2',
                type: "post",
                dataType: "json",
                data: {
                    "firstCategoryId": $("#WaresAddCategory1").val()
                },
                async: false,
                success: function (result) {
                    if (result.code === true) {
                        $("#WaresAddCategory2").empty();
                        for (var i = 0; i < result.category2.length; i++) {
                            $("#WaresAddCategory2").append("<option value=" + result.category2[i].categoryId + ">" + result.category2[i].categoryName + "</option>")
                        }
                    } else {
                        layer.msg(result.msg);
                    }
                }, error: function () {
                    layer.msg("拉取失败，稍后再试");
                }
            });
            getAllUnit();
            layer.open({
                type: 1,
                title: "创建商品",
                skin: 'layui-layer-rim',//加边框
                area: ['500px', '550px'],
                content: $("#WareAddView"),//注意放在<body>最外层
                btn: ['确认', '取消'],
                yes: function (index1, layero) {
                    if ($("#WaresAddId").val() != "" && $("#WaresAddId").val() == waresId) {//不能改为===
                        layer.msg("条码重复，请更换");
                        $("#WaresAddId").focus();
                        $("#WaresAddId").val("");
                    } else {
                        if (freshCheck("#WareAddView")) {
                            form.on('submit(waresAddView)', function () {
                                $("#waresAddView").ajaxSubmit({
                                    type: 'POST',
                                    url: "insertWares",
                                    dataType: 'json',
                                    success: function (result) {
                                        if (result.code === true) {
                                            layer.close(index1);
                                            table.reload('waresRender');
                                        } else {
                                            waresId = result.waresId;
                                            layer.msg(result.msg);
                                        }

                                    },

                                });
                                return false;   //防止表单自动提交
                            });
                            $("#waresAddView").submit();
                        }

                    }
                },
                btn2: function (index, layero) {
                    layer.close(index);
                },
            });
        });

    });

    function freshCheck(id) {
        //加个保鲜期小于保质期的验证
        var expDate = $(id).find("input[name$='expiryDate']");
        var freDate = $(id).find("input[name$='freshDate']");
        var purchase = $(id).find("input[name$='purchase']");
        var price = $(id).find("input[name$='price']");
        if (parseFloat(expDate.val()) < parseFloat(freDate.val())) {
            layer.tips("保鲜期不能大于保质期", freDate, {
                tips: [1, '#2B2B2B'],
                time: 2000
            });
            freDate.val("");
            freDate.focus();
            return false;
        } else if (parseFloat(purchase.val()) >= parseFloat(price.val())) {
            layer.tips("售价不能小于/等于进价", price, {
                tips: [1, '#2B2B2B'],
                time: 2000
            });
            price.val("");
            price.focus();
            return false;
        } else {
            return true
        }
    }

});
